#/bin/bash

if ! groups | grep -qw "kvm"; then
    echo "Please add user $USER to kvm group to run this script (usermod -aG kvm $USER and then log in again)."
    exit 1
fi

set -e

function launch_tdx_gpus() {
    local count=5
    for ((i=1; i<=count; i++))
    do
        echo "循环次数: $i"  
    done
}

function launch_tdx() {
    IMAGE=$1
    CPUS=$2
    MEMORY=$3
    SSH_PORT=$4
    MAC=$5
    VSOCK_CID=$6
    GPU_BDF=$7
    PCI_NUMBER=$8
    
    if [ ! -z ${GPU_BDF} ];then 
       GPU_ARGS="-object iommufd,id=iommufd${PCI_NUMBER} -device pcie-root-port,id=pci.${PCI_NUMBER},bus=pcie.0 -device vfio-pci,host=${GPU_BDF},bus=pci.${PCI_NUMBER},iommufd=iommufd${PCI_NUMBER} -fw_cfg name=opt/ovmf/X-PciMmio64,string=262144"
    fi 
    
qemu-system-x86_64 \
-enable-kvm -cpu host \
-drive file="${IMAGE}",if=virtio \
-object tdx-guest,id=tdx \
-smp "${CPUS}" \
-m "${MEMORY}G" -object memory-backend-ram,id=mem0,size="${MEMORY}G" \
-cpu host \
-device virtio-net-pci,netdev=nic0_td -netdev user,id=nic0_td,hostfwd=tcp::"${SSH_PORT}"-:22 \
-netdev bridge,br=virbr0,id=net0 -device virtio-net-pci,netdev=net0,mac="${MAC}" \
-nographic \
-daemonize \
-machine q35,kernel-irqchip=split,confidential-guest-support=tdx,memory-backend=mem0 \
-bios /shared/tdx-linux/edk2/OVMF.fd \
-vga none -nodefaults \
${GPU_ARGS} \
-device vhost-vsock-pci,guest-cid="${VSOCK_CID}"

}

function launch_tdx_test() {
    IMAGE=$1
    CPUS=$2
    MEMORY=$3
    SSH_PORT=$4
    MAC=$5
    VSOCK_CID=$6
    GPU_BDF=$7
    PCI_NUMBER=$8
    
    if [ -z ${GPU_BDF} ];then 
       GPU_ARGS="-object iommufd,id=iommufd${PCI_NUMBER} -device pcie-root-port,id=pci.${PCI_NUMBER},bus=pcie.0 -device vfio-pci,host=${GPU_BDF},bus=pci.${PCI_NUMBER},iommufd=iommufd${PCI_NUMBER} -fw_cfg name=opt/ovmf/X-PciMmio64,string=262144"
    fi 
    
qemu-system-x86_64 \
-enable-kvm -cpu host \
-drive file="${IMAGE}",if=virtio \
-object tdx-guest,id=tdx \
-smp "${CPUS}" \
-m "${MEMORY}G" -object memory-backend-ram,id=mem0,size="${MEMORY}G" \
-cpu host \
-device virtio-net-pci,netdev=nic0_td -netdev user,id=nic0_td,hostfwd=tcp::"${SSH_PORT}"-:22 \
-netdev bridge,br=virbr0,id=net0 -device virtio-net-pci,netdev=net0,mac="${MAC}" \
-nographic \
-daemonize \
-machine q35,kernel-irqchip=split,confidential-guest-support=tdx,memory-backend=mem0 \
-bios /shared/tdx-linux/edk2/OVMF.fd \
-vga none -nodefaults \
-device vhost-vsock-pci,guest-cid="${VSOCK_CID}" \
-object iommufd,id=iommufd"${PCI_NUMBER}" \
-device pcie-root-port,id=pci."${PCI_NUMBER}",bus=pcie.0 \
-device vfio-pci,host="${GPU_BDF}",bus=pci."${PCI_NUMBER}",iommufd=iommufd"${PCI_NUMBER}" \
-fw_cfg name=opt/ovmf/X-PciMmio64,string=262144
}


launch_tdx "$@"